function showFullScreenImage($scope, $ionicModal, $ionicSlideBoxDelegate) {
  $scope.openImageB64 = function (url, name, type) {
    window.FullScreenImage.showImageBase64(url, name, type);
  }

  $scope.openImageUrl = function (url) {
    window.FullScreenImage.showImageURL(url);
  }

  $ionicModal.fromTemplateUrl('image-modal-base64.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function (modal) {
    $scope.modalB64 = modal;
  });


  $scope.openModalB64 = function (position) {
    var position = position || 0;
    $ionicSlideBoxDelegate.slide(position);
    $scope.modalB64.show();
  };

  $scope.closeModalB64 = function () {
    $scope.modalB64.hide();
  };


  // Cleanup the modal when we're done with it!
  $scope.$on('$destroy', function () {
    $scope.modalB64.remove();
  });
  // Execute action on hide modal
  $scope.$on('modal.hide', function () {
    // Execute action
  });
  // Execute action on remove modal
  $scope.$on('modal.removed', function () {
    // Execute action
  });
  $scope.$on('modal.shown', function () {
    console.log('Modal is shown!');
  });

  // Call this functions if you need to manually control the slides
  $scope.next = function () {
    $ionicSlideBoxDelegate.next();
  };

  $scope.previous = function () {
    $ionicSlideBoxDelegate.previous();
  };

  $scope.goToSlide = function (index) {
    $scope.modal.show();
    $ionicSlideBoxDelegate.slide(index);
  }

  // Called each time the slide changes
  $scope.slideChanged = function (index) {
    $scope.slideIndex = index;
  };
}


angular.module('app.directives', [])


  .directive('ionImageScale', [function () {


    return {
      restrict: 'A',
      link: link
    };

    function link(scope, element, attrs) {

      var scaleImage = function (context, value) {
        if (value > 0) {
          if (context.naturalHeight >= context.naturalWidth) {
            element.attr('width', '100%');
          }
          else {
            element.attr('height', element.parent()[0].offsetHeight + 'px');
          }
        }
      };

      element.bind("load", function (e) {
        if (element.parent()[0].offsetHeight > 0) {
          scaleImage(this, element.parent()[0].offsetHeight);
        }
        else {
          var _this = this;
          scope.$watch(function () {
            return element.parent()[0].offsetHeight;
          }, function (newValue) {
            scaleImage(_this, newValue);
          });
        }
      });
    }
  }])
  /**
   * 照片的列表指令(在协警输入人员信息, 事件,车辆等地方都会用到该指令)
   */
  .directive('ionPhotoGrid', [function () {

    this.$inject = ['CommonService', '$ionicModal', '$ionicSlideBoxDelegate'];

    return {
      restrict: 'E', //E = element（元素）, A = attribute（属性）, C = class, M = comment
      scope: {
        ionPhotoItems: '=ionPhotoItems',
        ionPhotoNumPerRow: '=ionPhotoNumPerRow' //每列的元素个数
        , ionWithAddButton: '=ionWithAddButton',
        ionWithRemoveButton: '=ionWithRemoveButton',
        ionItemCallback: '=ionItemCallback',
        removeItemCallback: '=removeItemCallback',
        addAnotherCallback: '=addAnotherCallback',
        maxItemNum: "=maxItemNum",
        userDefaultEventHandler: "=userDefaultEventHandler"
      },
      controller: controller,//Embed a custom controller in the directive 在指令中嵌入一个自定义控制器
      templateUrl: 'templates/directive/ion-photo-grid.html',
      replace: false,
      link: function ($scope, element, attrs) {
      } //DOM manipulation DOM 操作
    };


    function controller($scope, $ionicModal, CommonService, $ionicSlideBoxDelegate) {

      showFullScreenImage($scope, $ionicModal, $ionicSlideBoxDelegate);


      var _drawGallery = function () {


        // 默认等于3行
        $scope.ionPhotoNumPerRow = $scope.ionPhotoNumPerRow || 3;
        //每列所占的行比例
        $scope.responsiveGrid = parseInt((1 / $scope.ionPhotoNumPerRow) * 100);

        //总的照片数量(多一张"+"图片)
        var totaltoItemNum = $scope.ionPhotoItems.length + 1;
        var mode = totaltoItemNum % $scope.ionPhotoNumPerRow;
        var divisionResult = Math.floor(totaltoItemNum / $scope.ionPhotoNumPerRow);
        var groupNum = mode == 0 ? divisionResult : divisionResult + 1;


        $scope.gridItImageIems = [];

        for (var groupIdx = 0; groupIdx < groupNum; groupIdx++) {

          var imageItem = [];
          $scope.gridItImageIems.push(imageItem);

          var tmp = (groupIdx + 1) * $scope.ionPhotoNumPerRow;

          for (var idx = $scope.ionPhotoNumPerRow * groupIdx; idx < tmp && idx < totaltoItemNum; idx++) {


            if (idx == totaltoItemNum - 1 && $scope.ionWithAddButton) {
              imageItem.push({
                isLast: true
              });
            } else {
              var photo = {
                thumb: $scope.ionPhotoItems[idx],
                position: idx,
                isLast: false
              }
              imageItem.push(photo);
            }

          }
        }


      };

      _drawGallery();

      (function () {
        $scope.$watch(function () {
          return $scope.ionPhotoItems.length;
        }, function (newVal, oldVal) {
          if (newVal !== oldVal) {
            _drawGallery();

            console.log(">>>>>>>>" + $scope.ionPhotoItems.length);
          }
        });
      }());

      //item click event call back
      $scope.customCallback = angular.isFunction($scope.ionItemCallback);
      //remove button call back
      $scope.isFunctionRemoveButtonCallback = angular.isFunction($scope.removeItemCallback);
      // add another photo button call back
      $scope.isFunctionAddButtonCallback = angular.isFunction($scope.addAnotherCallback);


      //简单处理时间穿透的问题
      var isRemove = false;
      //item点击事件
      $scope.diective_item_click = function (position) {

        $scope.openModalB64(position);
        return;

        if ($scope.customCallback && !isRemove) {
          $scope.ionItemCallback(position);
        }
      };
      $scope.diective_item_remove_click = function (position) {

        isRemove = true;
        setTimeout(function () {
          isRemove = false;
        }, 200);
        if ($scope.isFunctionRemoveButtonCallback) {
          $scope.removeItemCallback(position);
        } else {
          //使用默认的移除
          $scope.ionPhotoItems.splice(position, 1);
        }
      };
      $scope.diective_item_add_click = function (position) {

        if ($scope.isFunctionAddButtonCallback) {
          $scope.addAnotherCallback(position);
        } else {
          //获取图片
          CommonService.getPhoto().then(function (result) {
            $scope.ionPhotoItems.push(result);
          }, function (error) {
            alert("图片获取失败:" + error);
          })

        }
      }
    }

  }])
 .directive('ionPhotoGridViewer', [function () {

    this.$inject = ['$ionicModal', '$ionicSlideBoxDelegate'];

    return {
      restrict: 'E', //E = element（元素）, A = attribute（属性）, C = class, M = comment
      scope: {
        ionPhotoItems: '=ionPhotoItems',
        ionPhotoNumPerRow: '=ionPhotoNumPerRow' //每列的元素个数
      },
      controller: controller,//Embed a custom controller in the directive 在指令中嵌入一个自定义控制器
      templateUrl: 'templates/directive/ion-photo-grid-viewer.html',
      replace: false,
      link: function ($scope, element, attrs) {
      } //DOM manipulation DOM 操作
    };


    function controller($scope, $ionicModal, CommonService, $ionicSlideBoxDelegate) {

      showFullScreenImage($scope, $ionicModal, $ionicSlideBoxDelegate);


      var _drawGallery = function () {


        // 默认等于3行
        $scope.ionPhotoNumPerRow = $scope.ionPhotoNumPerRow || 3;
        //每列所占的行比例
        $scope.responsiveGrid = parseInt((1 / $scope.ionPhotoNumPerRow) * 100);


        var totaltoItemNum = $scope.ionPhotoItems.length ;
        var mode = totaltoItemNum % $scope.ionPhotoNumPerRow;
        var divisionResult = Math.floor(totaltoItemNum / $scope.ionPhotoNumPerRow);
        var groupNum = mode == 0 ? divisionResult : divisionResult + 1;


        $scope.gridItImageIems = [];

        for (var groupIdx = 0; groupIdx < groupNum; groupIdx++) {

          var imageItem = [];
          $scope.gridItImageIems.push(imageItem);

          var tmp = (groupIdx + 1) * $scope.ionPhotoNumPerRow;

          for (var idx = $scope.ionPhotoNumPerRow * groupIdx; idx < tmp && idx < totaltoItemNum; idx++) {
              var photo = {
                thumb: $scope.ionPhotoItems[idx],
                position: idx,
                isLast: false
              }
              imageItem.push(photo);
          }
        }


      };

      _drawGallery();

      (function () {
        $scope.$watch(function () {
          return $scope.ionPhotoItems.length;
        }, function (newVal, oldVal) {
          if (newVal !== oldVal) {
            _drawGallery();

            console.log(">>>>>>>>" + $scope.ionPhotoItems.length);
          }
        });
      }());


      //item click event call back
      $scope.customCallback = angular.isFunction($scope.ionItemCallback);

      //item点击事件
      $scope.diective_item_click = function (position) {

        $scope.openModalB64(position);
        return;

        if ($scope.customCallback && !isRemove) {
          $scope.ionItemCallback(position);
        }
      };

    }

  }])


  /**
   * 开始时间和截止时间选择控制
   */
  .directive('ionStartAndEndTimePicker', [function () {
    return {
      restrict: 'E', //E = element（元素）, A = attribute（属性）, C = class, M = comment
      //scope: false,
      controller: controller,//Embed a custom controller in the directive 在指令中嵌入一个自定义控制器
      templateUrl: 'templates/directive/ion-start-and-end-time-picker.html',
      replace: false,
      link: function ($scope, element, attrs) {
      } //DOM manipulation DOM 操作
    };


    function controller($scope, CommonService) {

      $scope.searchCondition = $scope.searchCondition || {};

      //选择开始时间
      $scope.inputQueryStartTime = function () {
        CommonService.getTimePicker().then(function (timeString, date) {
          $scope.searchCondition.beginCreateDate = timeString;

        });
      };
      $scope.inputQueryEndTime = function () {
        CommonService.getTimePicker().then(function (timeString, date) {
          $scope.searchCondition.endCreateDate = timeString;
        });
      };
    }
  }])
  /**
   * 身份证验证控件
   */
  .directive('ionIDValidate', [function () {
    return {
      restrict: 'A',
      link: link
    };
    function link(scope, element, attrs) {
      element.bind("load", function (e) {

      });
    }
  }])
;
